package com.hs.srm.admin.modules.requisition.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hs.srm.admin.modules.pricemanagement.vo.EssentialInformationVO;
import com.hs.srm.admin.modules.requisition.entity.ProPurchRequestHeaderEntity;
import com.hs.srm.admin.modules.requisition.entity.ProPurchRequestItemEntity;
import com.hs.srm.admin.modules.requisition.service.ProPurchRequestHeaderService;
import com.hs.srm.admin.modules.requisition.service.ProPurchRequestItemService;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.common.utils.DateUtils;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import sunnykid.text.SunnykidText;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author yanfei
 * @date 2019年2月14日
 * 生产性采购申请头信息
 */
@RestController
@RequestMapping("/proPurchRequestHeader")
@Transactional
public class ProPurchRequestHeaderController extends AbstractController {

    private static final long serialVersionUID = -4123823577744890422L;
    // 注入业务层
    @Autowired
    private ProPurchRequestHeaderService proPurchRequestHeaderService;
    @Autowired
    private ProPurchRequestItemService proPurchRequestItemService;

    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        params.put("purch_request_type", "zbz");
        // 查询用户列表
        PageUtils page = proPurchRequestHeaderService.queryPage(params);
        return R.ok(page);
    }

    @SysLog("保存申请采购抬头信息和行项目")
    @RequestMapping(value = "/save", produces = "application/json; utf-8")
    // 后台@RequestBody来标识需要从请求体中解析数据
    //@RequiresPermissions("vendorEnclosure:save")
    public R save(@RequestBody JSONObject obj) {
        String data = obj.toJSONString();
        //解析json数据
        JSONObject json = JSON.parseObject(data);
        //从json对象中拿到抬头信息后转换成对应的抬头对象
        JSONObject json_ = JSON.parseObject(json.getString("proPurchRequestHeaderEntity"));
        ProPurchRequestHeaderEntity proPurchRequestHeaderEntity = new ProPurchRequestHeaderEntity();
        ProPurchRequestItemEntity proPurchRequestItemEntity = new ProPurchRequestItemEntity();
        //采购申请行项目
        List<ProPurchRequestItemEntity> entityList = null;
        //采购组
        String purchGroup = json_.getString("purchGroup");
        if (json_ != null) {
            proPurchRequestHeaderEntity.setPkId(SunnykidText.getUUID());
            proPurchRequestHeaderEntity.setPurchRequestType(json_.getString("purchRequestType"));
            proPurchRequestHeaderEntity.setPurchRequestStaff(json_.getString("purchRequestStaff"));
            proPurchRequestHeaderEntity.setPurchRequestDept(json_.getString("purchRequestDept"));
        }
        JSONArray itmelist = JSONArray.parseArray(json.getString("proPurchRequestItemEntity"));
        for (int i = 0; i < itmelist.size(); i++) {
            JSONObject jo = JSONObject.parseObject(itmelist.getString(i));
            proPurchRequestItemEntity.setPurchGroup(purchGroup);
            proPurchRequestItemEntity.setPkId(SunnykidText.getUUID());
            entityList = new ArrayList<ProPurchRequestItemEntity>();

            for (String key : jo.keySet()) {
                if (key.equals("subjectCategory")) {
                    proPurchRequestItemEntity.setSubjectCategory(jo.getString(key));
                }
                if (key.equals("purchOrg")) {
                    proPurchRequestItemEntity.setPurchOrg(jo.getString(key));
                }
                if (key.equals("factory")) {
                    proPurchRequestItemEntity.setFactory(jo.getString(key));
                }
                if (key.equals("costCenter")) {
                    proPurchRequestItemEntity.setCostCenter(jo.getString(key));
                }
                if (key.equals("materialGroup")) {
                    proPurchRequestItemEntity.setMaterialGroup(jo.getString(key));
                }
                if (key.equals("usePeople")) {
                    proPurchRequestItemEntity.setUsePeople(jo.getString(key));
                }
                if (key.equals("materialDesc")) {
                    proPurchRequestItemEntity.setMaterialDesc(jo.getString(key));
                }
                if (key.equals("applyQty")) {
                    proPurchRequestItemEntity.setApplyQty(jo.getBigDecimal(key));
                }
                if (key.equals("measureUnit")) {
                    proPurchRequestItemEntity.setMeasureUnit(jo.getString(key));
                }
                if (key.equals("purchGroup")) {
                    proPurchRequestItemEntity.setSubjectCategory(jo.getString(key));
                }
                if (key.equals("requestDate")) {
                    proPurchRequestItemEntity.setRequestDate(jo.getSqlDate(key));
                }
                if (key.equals("deliveryDate")) {
                    proPurchRequestItemEntity.setDeliveryDate(jo.getSqlDate(key));
                }
                if (key.equals("deliveryAddress")) {
                    proPurchRequestItemEntity.setDeliveryAddress(jo.getString(key));
                }
                if (key.equals("mainAssetsCode")) {
                    proPurchRequestItemEntity.setMainAssetsCode(jo.getString(key));
                }
                if (key.equals("assetsSencondCode")) {
                    proPurchRequestItemEntity.setAssetsSencondCode(jo.getString(key));
                }
                if (key.equals("internalOrderCode")) {
                    proPurchRequestItemEntity.setInternalOrderCode(jo.getString(key));
                }
            }
            entityList.add(proPurchRequestItemEntity);
        }
        if (proPurchRequestHeaderEntity != null && proPurchRequestItemEntity != null) {
            this.proPurchRequestHeaderService.insert(proPurchRequestHeaderEntity);
            this.proPurchRequestItemService.insertBatch(entityList);
            return R.ok();
        }
        return R.ok();
    }

    /**
     * 跳转至采购单申请编辑页面
     *
     * @return
     */
    @RequestMapping("/toEdit/{pkId}")
    public ModelAndView toEdit(@PathVariable("pkId") String pkId) {
        //通过Id查询抬头信息
        ProPurchRequestHeaderEntity proPurchRequestHeaderEntity = this.proPurchRequestHeaderService.selectById(pkId);
        //采购申请单号
        String purchRequestCode = proPurchRequestHeaderEntity.getPurchRequestCode();
        List<ProPurchRequestItemEntity> itemlist = this.proPurchRequestItemService.findByNo(purchRequestCode, null);
        if (itemlist != null && itemlist.size() > 0) {
            for (ProPurchRequestItemEntity ite : itemlist) {
                //subjectCategory
                if ("K".equals(ite.getSubjectCategory())) {
                    ite.setSubjectCategory("K-成本中心");
                }
                if ("A".equals(ite.getSubjectCategory())) {
                    ite.setSubjectCategory("A-固定资产");
                }
                if ("F".equals(ite.getSubjectCategory())) {
                    ite.setSubjectCategory("F-在建工程");
                }
            }
        }
        //把查询出来的对象赋值给供应商实体
        ModelAndView modelAndView = new ModelAndView("modules/requisition/prorequisition_edit");
        modelAndView.addObject("proPurchRequestHeaderEntity", proPurchRequestHeaderEntity);
        modelAndView.addObject("itemlist", itemlist);
        return modelAndView;
    }

    /**
     * 更采购申请订单信息
     */
    @SysLog("修改供应商信息")
    @RequestMapping("/update")
    public R update(@RequestBody JSONObject obj) {
        String data = obj.toJSONString();
        //解析json数据
        JSONObject json = JSON.parseObject(data);
        //从json对象中拿到抬头信息后转换成对应的抬头对象
        JSONObject json_ = JSON.parseObject(json.getString("proPurchRequestHeaderEntity"));
        ProPurchRequestHeaderEntity proPurchRequestHeaderEntity = new ProPurchRequestHeaderEntity();
        ProPurchRequestItemEntity proPurchRequestItemEntity = new ProPurchRequestItemEntity();
        //采购申请行项目
        List<ProPurchRequestItemEntity> entityList = null;
        //采购组
        String purchGroup = json_.getString("purchGroup");
        if (json_ != null) {
            proPurchRequestHeaderEntity.setPkId(json_.getString("pkId"));
            proPurchRequestHeaderEntity.setPurchRequestType(json_.getString("purchRequestType"));
            proPurchRequestHeaderEntity.setPurchRequestStaff(json_.getString("purchRequestStaff"));
            proPurchRequestHeaderEntity.setPurchRequestDept(json_.getString("purchRequestDept"));
        }
        JSONArray itmelist = JSONArray.parseArray(json.getString("proPurchRequestItemEntity"));
        for (int i = 0; i < itmelist.size(); i++) {
            JSONObject jo = JSONObject.parseObject(itmelist.getString(i));

            proPurchRequestItemEntity.setPurchGroup(purchGroup);
            entityList = new ArrayList<ProPurchRequestItemEntity>();
            for (String key : jo.keySet()) {
                if (key.equals("pkId")) {
                    proPurchRequestItemEntity.setPkId(jo.getString(key));
                }
                if (key.equals("subjectCategory")) {
                    proPurchRequestItemEntity.setSubjectCategory(jo.getString(key));
                }
                if (key.equals("purchOrg")) {
                    proPurchRequestItemEntity.setPurchOrg(jo.getString(key));
                }
                if (key.equals("factory")) {
                    proPurchRequestItemEntity.setFactory(jo.getString(key));
                }
                if (key.equals("costCenter")) {
                    proPurchRequestItemEntity.setCostCenter(jo.getString(key));
                }
                if (key.equals("materialGroup")) {
                    proPurchRequestItemEntity.setMaterialGroup(jo.getString(key));
                }
                if (key.equals("usePeople")) {
                    proPurchRequestItemEntity.setUsePeople(jo.getString(key));
                }
                if (key.equals("materialDesc")) {
                    proPurchRequestItemEntity.setMaterialDesc(jo.getString(key));
                }
                if (key.equals("applyQty")) {
                    proPurchRequestItemEntity.setApplyQty(jo.getBigDecimal(key));
                }
                if (key.equals("measureUnit")) {
                    proPurchRequestItemEntity.setMeasureUnit(jo.getString(key));
                }
                if (key.equals("purchGroup")) {
                    proPurchRequestItemEntity.setSubjectCategory(jo.getString(key));
                }
                if (key.equals("requestDate")) {
                    proPurchRequestItemEntity.setRequestDate(jo.getSqlDate(key));
                }
                if (key.equals("deliveryDate")) {
                    proPurchRequestItemEntity.setDeliveryDate(jo.getSqlDate(key));
                }
                if (key.equals("deliveryAddress")) {
                    proPurchRequestItemEntity.setDeliveryAddress(jo.getString(key));
                }
                if (key.equals("mainAssetsCode")) {
                    proPurchRequestItemEntity.setMainAssetsCode(jo.getString(key));
                }
                if (key.equals("assetsSencondCode")) {
                    proPurchRequestItemEntity.setAssetsSencondCode(jo.getString(key));
                }
                if (key.equals("internalOrderCode")) {
                    proPurchRequestItemEntity.setInternalOrderCode(jo.getString(key));
                }
            }
            entityList.add(proPurchRequestItemEntity);
        }
        if (proPurchRequestHeaderEntity != null && proPurchRequestItemEntity != null) {
            this.proPurchRequestHeaderService.updateById(proPurchRequestHeaderEntity);
            this.proPurchRequestItemService.updateById(proPurchRequestItemEntity);
            return R.ok();
        }
        return R.ok();
    }

    /**
     * 货源指定信息(此处的数据要进订单表)
     */
    @SuppressWarnings("unused")
    @SysLog("货源指定信息")
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("/updateSource")
    public synchronized R updateSource(@RequestBody JSONObject obj) {
        return proPurchRequestHeaderService.updateSource(obj, this.getUser().getUsername());
    }

    /**
     * 询价
     *
     * @param
     * @return
     */
    @RequestMapping("/inquiry/{itemrowData}")
    public ModelAndView inquiry(@PathVariable("itemrowData") String itemrowData) {

        //行项目id
        List<String> pklist = new ArrayList<String>(itemrowData.split(",").length);
        Collections.addAll(pklist, itemrowData.split(","));
        List<ProPurchRequestItemEntity> itemlist = this.proPurchRequestItemService.selectBatchIds(pklist);
        //把查询出来的对象赋值给供应商实体
        ModelAndView modelAndView = new ModelAndView("modules/pricemanagement/inquiry/inquiry_add");
        modelAndView.addObject("itemlist", itemlist);
        modelAndView.getModel().put("companyCode", itemlist.get(0).getFactory());
        modelAndView.getModel().put("purchaseOrg", itemlist.get(0).getPurchOrg());
        modelAndView.getModel().put("purchaseGrp", itemlist.get(0).getPurchGroup());
        modelAndView.getModel().put("currency", itemlist.get(0).getCurrency());
        modelAndView.getModel().put("beginDate", DateUtils.getTime());

        return modelAndView;
    }


    /**
     * 生成报价单
     */
    @RequestMapping("/generateQuotations")
    public ModelAndView generateQuotations() {
        ModelAndView modelAndView = new ModelAndView("modules/pricemanagement/inquiry/inquiry_list");
        return modelAndView;
    }

    /**
     * 报价
     */
    @RequestMapping("/offer")
    public ModelAndView offer() {
        //把查询出来的对象赋值给供应商实体
        ModelAndView modelAndView = new ModelAndView("modules/pricemanagement/offer/offer_list");
        return modelAndView;
    }

    /**
     * 比价 （后续跟据要求可以做优化）
     */
    @RequestMapping("/parity")
    public ModelAndView parity() {
        //把查询出来的对象赋值给供应商实体
        ModelAndView modelAndView = new ModelAndView("modules/pricemanagement/parity/parity_list");

        return modelAndView;
    }

    /**
     * 从信息记录、货源记录中取数据，先保存分配货源数据，实现批量生成一个订单
     *
     * @param obj 分配货源数据
     * @return
     */
    @PostMapping("/saveDistributeData")
    public R saveDistributeData(@RequestBody JSONObject obj) {
        EssentialInformationVO informationVO = JSONObject.parseObject(obj.getJSONArray("essentialInformationVO").getJSONObject(0).getString("essentialInformationVO"), EssentialInformationVO.class);
        //通过申请编码、行项目获取申请单数据
        ProPurchRequestItemEntity itemEntity = proPurchRequestItemService.selectOne(new EntityWrapper<ProPurchRequestItemEntity>()
                .eq("purch_request_code", informationVO.getPurchRequestCode())
                .eq("purch_request_item_code", informationVO.getPurchRequestItemCode()));
        //供应商编码
        itemEntity.setVendorCode(informationVO.getSapCode());
        //供应商名称
        itemEntity.setVendorName(informationVO.getVendorName());
        //分配的货源记录数据以json格式保存
        itemEntity.setDistributeData(JSON.toJSONString(informationVO));
        proPurchRequestItemService.updateById(itemEntity);
        return R.ok();
    }
}
